package com.zhxy.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONUtils {
    public static final ObjectMapper OBJECT_MAPPER=new ObjectMapper();

    /**
     * 把java对象转换成JSON字符串
     * @param object
     * @return
     */
    public static String toJSON(Object object) {
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 把JSON字符串转换成java对象
     * @param json
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T toBean(String json,Class<T> clazz){
        try {
            return OBJECT_MAPPER.readValue(json,clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
